//index.js
//获取应用实例
const common = require('../../../public.js')
Page({
    data: {
        storeId: '',
        showLimit: '10',
        showGoodsLimit: '10',
        showHome: true,
        mainPageInfo: {},
        couponList: [],
        cateIndex: -1,
        headerSafeDis: 0,
        currentPanle: 1,
        height: '', //胶囊位置
        top: '', //胶囊位置
        isCollected: false,
        isLoading: true,
        commentList: [],
        storeName: '',
        storeImage: null
    },
    navbarBtn: {
        top: 0
    },
    onLoad: function (options) {
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
            storeId: options.id,
            storeName: options.storeName ? options.storeName : '',
            storeImage: options.storeImage ? options.storeImage : null
        })
        common.getLocalUserInfo((success, data) => {
            if (success) {
                this.setData({
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                    teamId: options.teamId ? options.teamId : null,
                    storeId: options.id,
                }, () => {
                    this.queryCollection()
                    this.getStoreMainPageInfo()
                })
            } else {
                this.getStoreMainPageInfo()
            }
        })
    },
    clickImg(e) {
        let index = e.currentTarget.dataset.index
        wx.previewImage({
            urls: [this.data.mainPageInfo.backUpPicList[index].pictureUrl] // 需要预览的图片http链接列表
        })
    },
    toWitness() {
        wx.navigateTo({
            url: '/pages/Goods/witness/index?storeId=' + this.data.storeId,
        })
    },
    toDraw(e) {
        let id = e.currentTarget.dataset.id
        console.log(id)
        wx.navigateTo({
            url: '/pages/draw/index?drawId=' + id,
        })
    },
    toZeroBuy(e) {
        // ../Zero/Des/index?id='+item.id+'&name='+item.goodsTitle
        let id = e.currentTarget.dataset.id
        let name = e.currentTarget.dataset.name

        wx.navigateTo({
            url: '/pages/Zero/Des/index?id=' + id + '&name=' + name,
        })
    },
    toCrow(e) {
        let {
            id
        } = e.currentTarget.dataset
        wx.navigateTo({
            url: '/pages/crowd/index/index?id=' + id
        })
    },
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.switchTab({
                url: '/pages/index/index',
            })
        }
    },
    toTeamStyle() {
        wx.navigateTo({
            url: '/pages/Goods/teamStyle/index?storeId=' + this.data.storeId,
        })
    },
    toTeamDetail(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/Goods/teamStyle/teamDetail/index?teamId=' + id,
        })
    },
    playWitness(e) { // 更新播放量
        console.log(e.currentTarget.dataset.id)
        let tempJson = {
            cwId: e.currentTarget.dataset.id
        }
        common.wxRequest("/store/updateWitnessClickNum", "post", tempJson, 'application/x-www-form-urlencoded', function (res) { })
    },
    showIntroduce() {
        this.setData({
            showHome: false,
        })
    },
    showStorePage() {
        this.setData({
            showHome: true,
        })
    },
    changeMarketingBtn(e) {
        // console.log(e.currentTarget.dataset.index)
        this.setData({
            currentPanle: e.currentTarget.dataset.index
        })
    },
    getStoreMainPageInfo() {
        const that = this
        const tempJson = {
            // xpoint: this.userPosition.xpoint,
            // ypoint: this.userPosition.ypoint,
            storeId: this.data.storeId
        }
        common.post('/store/mainPageInfo', tempJson, function (res) {
            if (res.status === 200) {
                for (let i = 0; i < res.data.couponList.length; i++) {
                    const startTimeStr = res.data.couponList[i].beginTime
                    const endTimeStr = res.data.couponList[i].finishTime
                    res.data.couponList[i].beginTime = that.timestampToTime(startTimeStr)
                    res.data.couponList[i].finishTime = that.timestampToTime(endTimeStr)
                }
                if (res.data.zeroGoodsList) {
                    for (let i = 0; i < res.data.zeroGoodsList.length; i++) {
                        // var endTimeStr =  res.data.zeroGoodsList[i].dayTime;   
                        const TimeDifStr = res.data.zeroGoodsList[i].endTime - res.data.zeroGoodsList[i].startTime
                        res.data.zeroGoodsList[i].day = that.toDay(TimeDifStr)
                        res.data.zeroGoodsList[i].hour = that.toHour(TimeDifStr)
                        res.data.zeroGoodsList[i].minute = that.toHour(TimeDifStr)
                    }
                }
                that.setData({
                    mainPageInfo: res.data,
                    couponList: res.data.couponList,
                    storeCatList: res.data.itemCatList2.storeCatList,
                    defaultItemList: res.data.itemCatList2.defaultItemList,
                    commentList: res.data.commentList,
                    zeroGoodsList: res.data.zeroGoodsList ? res.data.zeroGoodsList : null,
                    isLoading: false,
                    storeImage: (res.data.store && res.data.store.storeImage) ? res.data.store.storeImage : null,
                    storeName: (res.data.store && res.data.store.name) ? res.data.store.name : ''
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoading: false
            })
        })
    },
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.mainPageInfo.store.mobile,
            fail: function () { }
        })
    },
    timestampToTime(timestamp) {
        var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = date.getDate() + '';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        return Y + M + D; //时分秒可以根据自己的需求加上
    },
    clickCollect() {
        let that = this
        wx.getStorage({ //获取本地缓存
            key: 'user',
            success(res) {
                that.setData({
                    userInfo: res.data.user,
                    openid: res.data.openid,
                }, function () {
                    let param = that.data.isCollected ? 'delete' : 'add'
                    var tempJson = {
                        token: that.data.token,
                        userId: that.data.userInfo.id,
                        storeId: that.data.storeId
                    };
                    common.post("/store/favo/" + param, tempJson, function (res) {
                        res.status == 200 && that.queryCollection()
                    })
                })
            },
            fail: function (res) {
                common.showLoginPage()
            },
        })

    },
    queryCollection() {
        var that = this
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/collected", tempJson, function (res) {
            // 当前接口200是关注，非200是未关注
            that.setData({
                isCollected: res.data
            })
        });
    },

    toDay(timestamp) {
        var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var D = date.getDate() + '';
        console.log('天数为', D);
        return D;
    },

    toHour(timestamp) {
        var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var h = date.getHours();
        console.log('h为', h);
        return h;
    },
    toMinute(timestamp) {
        var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var m = date.getMinutes();
        return m;
    },

    immediateClick(e) {
        const idx = e.currentTarget.dataset.id
        var that = this;
        wx.getStorage({
            key: 'user',
            success: function (res) {
                that.setData({
                    userInfo: res.data.user,
                    token: res.data.token,
                    openid: res.data.openid
                    // itemId: that.options.id,
                })
                that.getVoucher(idx);
            },
            fail: function (res) {
                common.showLoginPage()
            }
        })
    },
    changeCategory(idx) {
        this.setData({
            isLoading: true
        })
        const that = this
        const tempJson = {
            cid: idx,
            storeId: that.data.storeId,
            token: that.data.token,
            userId: that.data.userInfo.id
        }
        common.post('/store/mainPageInfo/cid', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    defaultItemList: res.data.data
                })
            } else {
                that.setData({
                    defaultItemList: []
                })
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoading: false
            })
        })
    },
    categoryClick(e) {
        const idx = e.currentTarget.dataset.id
        const index = e.currentTarget.dataset.index;
        if (this.data.cateIndex === index) {
            return
        }
        const that = this
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                    cateIndex: index
                })
                that.changeCategory(idx)
            }
        }, true)
    },
    getVoucher(idx) {
        var that = this;
        var tempJson = {
            discountCouponId: idx,
            source: 1, // 1为手动领取，2为系统群发
            token: that.data.token,
            userId: that.data.userInfo.id
        };
        common.wxRequest("/discountCoupon/getShopCoupon", "get", tempJson, 'application/x-www-form-urlencoded', function (res) {
            console.log(res);
            if (res.status == 200) {
                wx.showToast({
                    title: '领取成功',
                    icon: "none"
                })
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '领取失败',
                    icon: "none"
                })
            }
        })
    },
    goodsImgClick(e) {
        const idx = e.currentTarget.dataset.item.goodsId
        const title = e.currentTarget.dataset.item.goodsTitle
        wx.navigateTo({
            url: '/pages/Goods/GoodsDes/index?id=' + idx + '&name=' + title + '&isVip=' + true,
        })
    },
    goodsDetail(e) {
        common.gotoGoodsPage(e.currentTarget.dataset.item)
    },
    checkAddress() { //点击地址按钮
        if (!this.data.mainPageInfo.store.xpoint || !this.data.mainPageInfo.store.ypoint) {
            common.showToast('商家未设置位置信息')
            return
        }
        let lon = parseFloat(this.data.mainPageInfo.store.xpoint)
        let lat = parseFloat(this.data.mainPageInfo.store.ypoint)
        wx.openLocation({
            latitude: lat,
            longitude: lon,
            name: this.data.mainPageInfo.store.name ? this.data.mainPageInfo.store.name : null,
            address: this.data.mainPageInfo.store.address ? this.data.mainPageInfo.store.address : null,
            scale: 18,
            fail: () => {
                wx.showToast({
                    title: '无地址信息',
                    icon: 'none'
                })
            }
        })
    },
    seeAllEvaluateClick() { // 查看更多评论
        this.setData({
            showLimit: this.data.mainPageInfo.commentCount
        })
    },
    showMoreGoods() { // 查看更多商品
        this.setData({
            showGoodsLimit: this.data.mainPageInfo.itemCount
        })
    },
    hideEvaluate() {
        this.setData({
            showLimit: 10
        })
    },
    onShareAppMessage: function () {
        return {
            title: this.data.mainPageInfo.store.name,
            path: 'pages/Goods/storePage/index?id=' + this.data.storeId,
            // imageUrl: '/images/home.png',
            success: (res) => {
                // 分享成功
            },
            fail: (res) => {
                // 分享失败
            }
        }
    },
    onShareTimeline() {
        return {
            title: this.data.storeName,
            query: 'id=' + this.data.storeId,
            imageUrl: this.data.storeImage
        }
    }
})